// scripts/test_organization_switch.js
const { Sequelize, DataTypes } = require('sequelize');

// 数据库配置
const sequelize = new Sequelize('lingxi_system', 'root', '888mei525', {
  host: '127.0.0.1',
  dialect: 'mysql',
  logging: false
});

// 定义模型
const User = sequelize.define('user', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  name: {
    type: DataTypes.STRING(50),
    allowNull: false
  },
  email: {
    type: DataTypes.STRING(100),
    allowNull: false,
    unique: true
  },
  password: {
    type: DataTypes.STRING(100),
    allowNull: false
  },
  role: {
    type: DataTypes.ENUM('admin', 'user', 'auditor'),
    defaultValue: 'user'
  },
  status: {
    type: DataTypes.ENUM('active', 'inactive', 'locked'),
    defaultValue: 'active'
  }
}, {
  tableName: 'users',
  timestamps: true,
  underscored: true
});

const Organization = sequelize.define('organization', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  name: {
    type: DataTypes.STRING(100),
    allowNull: false
  },
  code: {
    type: DataTypes.STRING(50),
    allowNull: false,
    unique: true
  },
  status: {
    type: DataTypes.ENUM('active', 'inactive'),
    defaultValue: 'active'
  }
}, {
  tableName: 'organizations',
  timestamps: true,
  underscored: true
});

const UserOrganization = sequelize.define('user_organization', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  userId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    field: 'user_id'
  },
  organizationId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    field: 'organization_id'
  },
  role: {
    type: DataTypes.STRING(50)
  },
  status: {
    type: DataTypes.ENUM('active', 'inactive'),
    defaultValue: 'active'
  }
}, {
  tableName: 'user_organizations',
  timestamps: true,
  underscored: true
});

// 建立关联关系
User.belongsToMany(Organization, {
  through: UserOrganization,
  foreignKey: 'user_id',
  otherKey: 'organization_id',
  as: 'organizations'
});

Organization.belongsToMany(User, {
  through: UserOrganization,
  foreignKey: 'organization_id',
  otherKey: 'user_id',
  as: 'users'
});

UserOrganization.belongsTo(User, {
  foreignKey: 'user_id',
  as: 'user'
});

UserOrganization.belongsTo(Organization, {
  foreignKey: 'organization_id',
  as: 'organization'
});

async function testOrganizationSwitch() {
  try {
    // 测试数据库连接
    await sequelize.authenticate();
    console.log('数据库连接成功');

    // 创建测试用户
    const [user, userCreated] = await User.findOrCreate({
      where: { email: 'test@example.com' },
      defaults: {
        name: '测试用户',
        email: 'test@example.com',
        password: 'password123',
        role: 'user'
      }
    });

    console.log('用户创建/查找结果:', userCreated ? '新建' : '已存在', user.toJSON());

    // 创建测试组织
    const [org1, org1Created] = await Organization.findOrCreate({
      where: { code: 'TEST001' },
      defaults: {
        name: '测试组织1',
        code: 'TEST001',
        status: 'active'
      }
    });

    const [org2, org2Created] = await Organization.findOrCreate({
      where: { code: 'TEST002' },
      defaults: {
        name: '测试组织2',
        code: 'TEST002',
        status: 'active'
      }
    });

    console.log('组织创建/查找结果:');
    console.log('组织1:', org1Created ? '新建' : '已存在', org1.toJSON());
    console.log('组织2:', org2Created ? '新建' : '已存在', org2.toJSON());

    // 将用户添加到组织
    const [userOrg1, userOrg1Created] = await UserOrganization.findOrCreate({
      where: { userId: user.id, organizationId: org1.id },
      defaults: {
        userId: user.id,
        organizationId: org1.id,
        role: 'manager'
      }
    });

    const [userOrg2, userOrg2Created] = await UserOrganization.findOrCreate({
      where: { userId: user.id, organizationId: org2.id },
      defaults: {
        userId: user.id,
        organizationId: org2.id,
        role: 'member'
      }
    });

    console.log('用户组织关联结果:');
    console.log('关联组织1:', userOrg1Created ? '新建' : '已存在');
    console.log('关联组织2:', userOrg2Created ? '新建' : '已存在');

    // 查询用户所属的所有组织
    const userWithOrganizations = await User.findByPk(user.id, {
      include: [{
        model: Organization,
        as: 'organizations',
        through: { attributes: ['role'] }
      }]
    });

    console.log('\n用户所属组织:');
    userWithOrganizations.organizations.forEach(org => {
      console.log(`- ${org.name} (${org.code}) - 角色: ${org.user_organization.role}`);
    });

    // 测试组织切换逻辑
    console.log('\n=== 组织切换测试 ===');
    
    // 模拟用户选择组织1
    const selectedOrg1 = userWithOrganizations.organizations.find(org => org.id === org1.id);
    if (selectedOrg1) {
      console.log(`用户切换到组织: ${selectedOrg1.name}`);
      console.log(`用户在该组织的角色: ${selectedOrg1.user_organization.role}`);
    }

    // 模拟用户选择组织2
    const selectedOrg2 = userWithOrganizations.organizations.find(org => org.id === org2.id);
    if (selectedOrg2) {
      console.log(`用户切换到组织: ${selectedOrg2.name}`);
      console.log(`用户在该组织的角色: ${selectedOrg2.user_organization.role}`);
    }

    await sequelize.close();
  } catch (error) {
    console.error('测试过程中发生错误:', error.message);
  }
}

testOrganizationSwitch();